﻿using Cmsp3.Common.Domains;
using Demo.PetaPoco.Application.DbContexts;
using Microsoft.Extensions.DependencyInjection;
using PetaPoco;
using PmSoft.Cache.Abstractions;
using PmSoft.Core;
using PmSoft.Data.PetaPoco.Repositories;

namespace Demo.PetaPoco.Application.Services.User;

[Inject(ServiceLifetime.Scoped)]
public class UserRoleRepository : CacheRepository<AppDbContext, SysUserRole, int>
{
	public UserRoleRepository(AppDbContext dbContext, IApplicationContext applicationContext) : base(dbContext, applicationContext)
	{
	}

	public async Task<IEnumerable<SysUserRole>> GetUserRolesAsync(int userId)
	{
		int areaVersion = await CacheVersionService.GetAreaVersionAsync(m => m.UserId, userId);
		return await GetTopEntitiesWithCacheAsync(1000,
			CachingExpirationType.UsualObjectCollection,
			() => $"UserRoles:{userId}:{areaVersion}",
			() =>
		{
			Sql sql = Sql.Builder.Select("id").From("sys_user_role").Where("user_id=@0", userId);
			return sql;
		});
	}
}
